import React from 'react'
import { useRequest } from 'ahooks'
import { changePw } from '@/apis'

import { Input, Modal, Form, Button } from 'antd'

import { Token, UserInfo } from '@/apis/config'

const { Password } = Input

const ChangePwModal = ({ open, firstLogin, account, onCancel }) => {
  const [form] = Form.useForm()

  const { run: onOk, loading } = useRequest(
    async () => {
      const values = await form.validateFields()

      return changePw({
        account,
        newPwd: btoa(values.newPw),
        originPwd: btoa(values.password)
      })
    },
    {
      manual: true,
      onSuccess: (res) => {
        onCancel()
        if(!res) return; 
        React.$message.success('修改成功')
        Token.set(res.token)
        UserInfo.set({
          account: res.account,
          passwdExpired: res.passwdExpired,
          tenantName: res.tenantName
        })
        location.reload()
        onCancel()
      }
    }
  )

  return (
    <Modal
      title="修改密码"
      open={open}
      onCancel={onCancel}
      confirmLoading={loading}
      closable={!firstLogin}
      keyboard={!firstLogin}
      footer={
        <>
          {!firstLogin && <Button onClick={onCancel}>取消</Button>}

          <Button type="primary" onClick={onOk}>
            保存
          </Button>
        </>
      }
      maskClosable={false}
      centered
    >
      {firstLogin && (
        <p className="mt-16 text-center">首次登录系统后，请修改密码，避免账号被盗用</p>
      )}

      <Form className="mt-16 pb-36" labelCol={{ span: 8 }} form={form}>
        <Form.Item label="账号">{account}</Form.Item>

        <Form.Item label="原密码" name="password" rules={[{ required: true }]}>
          <Password className="w-[236px]" placeholder="请输入原密码" />
        </Form.Item>

        <Form.Item label="新密码" name="newPw" rules={[{ required: true }]}>
          <Password className="w-[236px]" placeholder="请输入新密码" />
        </Form.Item>

        <Form.Item
          label="确认密码"
          name="confirmPW"
          dependencies={['password']}
          rules={[
            {
              required: true,
              message: '请输入确认密码'
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPw') === value) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error('两次输入的密码不一致，请重新输入'))
              }
            })
          ]}
        >
          <Password className="w-[236px]" placeholder="请输入确认密码" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default ChangePwModal
